package dev.mcdd.security.handler;


import dev.mcdd.common.helper.HttpHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author mcdd1024
 * @name AuthenticationExceptionHandler
 * @since 2025/1/16 08:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthenticationExceptionHandler implements AccessDeniedHandler, AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        try (PrintWriter writer = HttpHelper.responseWriterCustomer(response)) {
            writer.write("access denied");
        }
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        try (PrintWriter writer = HttpHelper.responseWriterCustomer(response)) {
            writer.write("access denied");
        }
    }
}
